package com.example.yiwei.crm.view.activity.healthActivity;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.dao.dockDao;
import com.example.yiwei.crm.dao.managerDao;
import com.example.yiwei.crm.dao_impl.dockDaoImpl;
import com.example.yiwei.crm.dao_impl.managerDaoImpl;
import com.example.yiwei.crm.data.GetDock;
import com.example.yiwei.crm.data.GetDockData;
import com.example.yiwei.crm.entity.dockingEntity;
import com.example.yiwei.crm.entity.managerEntity;
import com.example.yiwei.crm.util.NetWorkUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class healthEducationAddActivity extends AppCompatActivity {
    private Spinner spinner_manager;
    private EditText edit_docking_name,edit_docking_mechanism,edit_mechanism_attribute,edit_department,
            edit_professional_title,edit_phone_number,edit_additional;
    private TextView txt_address;
    private Button btn_show;
    private ImageView img_back,img_commit;
    private JSONObject mJsonObj;
    private String Filename;
    private List<String> name_list=new ArrayList<>();
    private TextView mtCity;
    // 省数据集合
    private ArrayList<String> mListProvince = new ArrayList<String>();
    // 市数据集合
    private ArrayList<ArrayList<String>> mListCiry = new ArrayList<ArrayList<String>>();
    // 区数据集合
    private ArrayList<ArrayList<ArrayList<String>>> mListArea = new ArrayList<ArrayList<ArrayList<String>>>();
    private OptionsPickerView<String> mOpv;
    String tx;
    List<managerEntity> managerList;
    private ArrayAdapter adapter1;
    private String managerName;
    private int manager_id;
    List<dockingEntity> dockinglist;
    private TextView txt_title;
    dockingEntity docking;
    dockingEntity dockingEntity;
    String manager_name;
    int dock_id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_health_education_add);
        img_back= (ImageView) findViewById(R.id.health_education_add_img_back);
        img_commit= (ImageView) findViewById(R.id.health_education_add_img_commit);
        btn_show= (Button) findViewById(R.id.health_education_add_btn_show);
        txt_address= (TextView) findViewById(R.id.health_education_add_txt_address);
        edit_docking_name= (EditText) findViewById(R.id.health_education_add_edit_docking_name);
        edit_docking_mechanism= (EditText) findViewById(R.id.health_education_add_edit_docking_mechanism);
        edit_mechanism_attribute= (EditText) findViewById(R.id.health_education_add_edit_mechanism_attribute);
        edit_department= (EditText) findViewById(R.id.health_education_add_edit_department);
        edit_professional_title= (EditText) findViewById(R.id.health_education_add_edit_professional_title);
        edit_phone_number= (EditText) findViewById(R.id.health_education_add_edit_phone_number);
        edit_additional= (EditText) findViewById(R.id.health_education_add_edit_additional);
        spinner_manager= (Spinner) findViewById(R.id.health_education_add_spinner_manager);
        txt_title= (TextView) findViewById(R.id.healt_education_add_txt_title);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        docking=GetDock.get();
        dock_id=docking.getDocking_id();
        initJsonData(this);
        // 初始化Json数据
        initJsonDatas();
        // 创建选项选择器对象
        mOpv = new OptionsPickerView<String>(this);
        // 设置标题
        mOpv.setTitle("选择城市");
        // 设置三级联动效果
        mOpv.setPicker(mListProvince, mListCiry, mListArea, true);
        // 设置是否循环滚动
        mOpv.setCyclic(false, false, false);
        // 设置默认选中的三级项目
        mOpv.setSelectOptions(0, 0, 0);
        // 监听确定选择按钮
        mOpv.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                // 返回的分别是三个级别的选中位置
                tx = mListProvince.get(options1) + mListCiry.get(options1).get(option2) + mListArea.get(options1).get(option2).get(options3);
                txt_address.setText(tx);
            }
        });
        btn_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOpv.show();
            }
        });
        if ("update".equals(getIntent().getStringExtra("tag"))){
            txt_title.setText("修改对接人");
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                managerDao manaDao=new managerDaoImpl();
                managerList=manaDao.queryAllManager(baseClass.query_manager_url,null);
                name_list.add(0,"");
                for (int i2=0;i2<managerList.size();i2++){
                    name_list.add( managerList.get(i2).getManager_name());
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter1 = new ArrayAdapter(healthEducationAddActivity.this,android.R.layout.simple_spinner_item, name_list);
                        spinner_manager.setAdapter(adapter1);
                        spinner_manager.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                managerName=spinner_manager.getSelectedItem().toString();
                                for (int i1 = 0;i1<managerList.size();i1++){
                                    if (managerName.equals(managerList.get(i1).getManager_name())){
                                        manager_id = Integer.valueOf(managerList.get(i1).getManager_id());
                                    }
                                }
                                if ("update".equals(getIntent().getStringExtra("tag"))){
                                    showMessage();
                                }
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });
                    }
                });
            }
        }).start();

        img_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               new Thread(new Runnable() {
                   @Override
                   public void run() {
                       JSONObject object=new JSONObject();
                       try {
                           if ("update".equals(getIntent().getStringExtra("tag"))){
                               docking=GetDock.get();
                               object.put("KDA01",docking.getDocking_id());
                           }
                           object.put("KDA15",managerName);
                           object.put("KDA26",manager_id);
                           object.put("KDA02",edit_docking_name.getText().toString());

                           object.put("KDA03",edit_docking_mechanism.getText().toString());
                           object.put("KDA04",edit_mechanism_attribute.getText().toString());
                           object.put("KDA05",edit_department.getText().toString());
                           object.put("KDA06",edit_professional_title.getText().toString());
                           object.put("KDA08",edit_phone_number.getText().toString());
                           object.put("KDA27",txt_address.getText().toString());
                           object.put("REK01",edit_additional.getText().toString());
                           object.put("CID01",-1);
                           String json=object.toString();
                           String result;
                           if ("update".equals(getIntent().getStringExtra("tag"))){
                               docking=GetDock.get();
                                result=NetWorkUtils.getCount(baseClass.update_docking_message_url+docking.getDocking_id(),json);
                           }else{
                                result=NetWorkUtils.getCount(baseClass.add_docking_message_url,json);
                           }
                           JSONObject object1=new JSONObject(result);
                           String boolen=object1.getString("boolean");
                           if ("success".equals(boolen)){
                                 new Thread(new Runnable() {
                                     @Override
                                     public void run() {
                                         dockDao dockDao = new dockDaoImpl();
                                         if ("update".equals(getIntent().getStringExtra("tag"))){
                                         dockingEntity = dockDao.queryDtailedDockingMessage(baseClass.query_detailed_docking_message_url + dock_id, null);
                                         GetDock.create();
                                         GetDock.dockingEntity = dockingEntity;
                                         if (dockingEntity != null) {
                                             finish();
                                         }
                                     }else {
                                             dockinglist = new ArrayList<dockingEntity>();
                                             dockinglist = dockDao.queryAllDockingMessage(baseClass.query_docking_message_url, null);
                                             GetDockData.create();
                                             GetDockData.dockingEntityList = dockinglist;
                                             if (dockinglist.size() != 0) {
                                                 finish();
                                             }
                                         }
                                     }
                                 }).start();
                             }
                       } catch (JSONException e) {
                           e.printStackTrace();
                       }

                   }
               }).start();

            }
        });
    }
    public void showMessage(){
        docking= GetDock.get();
        edit_department.setText(docking.getDepartment());
        edit_docking_name.setText(docking.getDocking_name());
        edit_docking_mechanism.setText(docking.getDocking_mechanism());
        edit_mechanism_attribute.setText(docking.getMechanism_attribute());
        edit_professional_title.setText(docking.getProfessional_title());
        edit_phone_number.setText(docking.getPhone_number());
        txt_address.setText(docking.getAddress());
        edit_additional.setText(docking.getAddtional_remark());
        SpinnerAdapter spadapter2 = spinner_manager.getAdapter();
        for (int i=0;i<managerList.size();i++) {
            if (docking.getManager_id() == managerList.get(i).getManager_id()) {
                manager_name =managerList.get(i).getManager_name();
            }
        }
        if (docking.getManager()!=null){
            for (int i = 0;i<spadapter2.getCount();i++){
                if (docking.getManager().equals(spadapter2.getItem(i).toString())){
                    spinner_manager.setSelection(i);
                }
            }
        }
    }
    /**
     * 从assert文件夹中读取省市区的json文件，然后转化为json对象
     */
    private void initJsonData(Context context) {
        Filename = "city.json";
        try {
            StringBuffer sb = new StringBuffer();
            AssetManager am = context.getAssets();
            InputStream is = am.open(Filename);
            int len = -1;
            byte[] buf = new byte[1024];
            while ((len = is.read(buf)) != -1) {
                sb.append(new String(buf, 0, len, "GBK"));
            }
            is.close();
            mJsonObj = new JSONObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化Json数据，并释放Json对象
     */
    private void initJsonDatas() {
        try {
            JSONArray jsonArray = mJsonObj.getJSONArray("citylist");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonP = jsonArray.getJSONObject(i);// 获取每个省的Json对象
                String province = jsonP.getString("name");
                ArrayList<String> options2Items_01 = new ArrayList<String>();
                ArrayList<ArrayList<String>> options3Items_01 = new ArrayList<ArrayList<String>>();
                JSONArray jsonCs = jsonP.getJSONArray("city");
                for (int j = 0; j < jsonCs.length(); j++) {
                    JSONObject jsonC = jsonCs.getJSONObject(j);// 获取每个市的Json对象
                    String city = jsonC.getString("name");
                    options2Items_01.add(city);// 添加市数据
                    ArrayList<String> options3Items_01_01 = new ArrayList<String>();
                    JSONArray jsonAs = jsonC.getJSONArray("area");
                    for (int k = 0; k < jsonAs.length(); k++) {
                        options3Items_01_01.add(jsonAs.getString(k));// 添加区数据
                    }
                    options3Items_01.add(options3Items_01_01);
                }
                mListProvince.add(province);// 添加省数据
                mListCiry.add(options2Items_01);
                mListArea.add(options3Items_01);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mJsonObj = null;
    }

}
